clear all;
%k=2; % Number of clusters
k=4;
%k=8;
%k=16;
A = double(imread('leslie-small.png')); % read the small image
n=size(A,1)*size(A,2); % Size of the data set

% Setting the centers of clusters
C = cell(k,1);
X1 = round(size(A,1)*rand(k,1));
X2 = round(size(A,2)*rand(k,1));
for i=1:k
    temp = A(X1(i),X2(i),:,:);
    C{i} = temp(:);
end
Centre = [C{:}]';
R = A(:,:,1);
G = A(:,:,2);
B = A(:,:,3);
data = [R(:) G(:) B(:)];
clear R G B;
clear C;
clear i temp X1 X2;

SSE_2 = 1e10;
SSE_1 = 1e9;

counter = 0;
max_iter = 200;

while SSE_1 < SSE_2 && counter < max_iter
    disp(['number of iteration: ', num2str(counter)]);
    
    % new cluster
    P = zeros(n,1);
    temp = zeros(k,size(A,3));
    N = zeros(k,1);
    s = zeros(k,1);
    for j=1:n
        v = (Centre - repmat(data(j,:),k,1))';
        v = sum(v.^2);
        [~,ind] = min(v);
        P(j) = ind;
    end
    
    for j=1:n
        temp(P(j),:) = temp(P(j),:) + data(j,:);
        N(P(j)) = N(P(j)) + 1;
    end
    
    Centre = temp./(repmat(N,1,size(A,3)));
    
    for j=1:n
        s(P(j)) = s(P(j)) + norm(Centre(P(j),:)-data(j,:))^2;
    end
    
    SSE_2 = SSE_1;
    SSE_1 = sum(s);
    
    counter = counter + 1;
end

Centre = round(Centre);
large_image = double(imread('leslie-big.png')); % need to change
r1 = size(large_image,1);
r2 = size(large_image,2);
for i=1:r1
    for j=1:r2
        r = large_image(i,j,1); g = large_image(i,j,2); b = large_image(i,j,3);
        diff = repmat([r g b],k,1) - Centre;
        [~,ind] = min(sum(diff.^2,2));
        large_image(i,j,:) = Centre(ind,:);
    end
end
figure;
imshow(uint8(round(large_image))); hold off

imwrite(uint8(round(large_image)), 'leslie_kmeans.jpg'); % can be changed





